package org.hfy.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.hfy.dto.LoginRequestDTO;
import org.hfy.dto.LoginResponseDTO;
import org.hfy.entity.Employee;
import org.hfy.exception.BusinessException;
import org.hfy.mapper.EmployeeMapper;
import org.hfy.service.AuthService;
import org.hfy.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 身份验证Service实现类
 * 
 * @author hfy
 * @version 1.0
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public LoginResponseDTO login(LoginRequestDTO loginRequest) {
        // 根据员工代码查询员工
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_code", loginRequest.getEmployeeCode());
        queryWrapper.eq("deleted", 0);
        Employee employee = employeeMapper.selectOne(queryWrapper);
        
        // 验证员工是否存在
        if (employee == null) {
            throw new BusinessException("员工不存在");
        }
        
        // 验证员工状态
        if (!"active".equals(employee.getStatus())) {
            throw new BusinessException("员工已停用");
        }
        
        // 验证密码
        String encryptedPassword = DigestUtil.md5Hex(loginRequest.getPassword());
        if (employee.getPassword() == null || !employee.getPassword().equals(encryptedPassword)) {
            throw new BusinessException("密码错误");
        }
        
        // 生成token
        String token = jwtUtils.generateToken(employee);
        
        // 返回登录信息
        return new LoginResponseDTO()
                .setId(employee.getId())
                .setEmployeeCode(employee.getEmployeeCode())
                .setEmployeeName(employee.getEmployeeName())
                .setRole(employee.getRole())
                .setToken(token);
    }

    @Override
    public boolean validateToken(String token) {
        return jwtUtils.validateToken(token);
    }
} 